<template>
  <var-form @submit="handleSubmit">
    <var-space direction="column" :size="[14, 0]">
      <var-input
        autofocus
        placeholder="手机号"
        :rules="[v => !!v || '手机号不能为空', validatePhone]"
        v-model="formData.phone"
      />
      <var-input
        placeholder="验证码"
        :rules="[v => !!v || '验证码不能为空']"
        v-model="formData.code"
      >
        <template #append-icon>
          <var-link
            v-if="showSendCode"
            @click="getCode"
            type="primary"
            underline="none"
            >获取验证码</var-link
          >
          <var-countdown
            v-else
            @end="showSendCode = true"
            format="重发(ss)"
            :time="60 * 1000"
          />
        </template>
      </var-input>
      <var-input
        type="password"
        placeholder="密码"
        :rules="[v => !!v || '密码不能为空']"
        v-model="formData.password"
      />
      <var-input
        type="password"
        placeholder="确认密码"
        :rules="[
          v => !!v || '确认密码不能为空',
          v => v === formData.password || '两次密码输入不一致'
        ]"
        v-model="confirmPassword"
      />
    </var-space>
    <div class="link">
      <span></span>
      <var-link to="/login" type="primary" underline="none">返回登录</var-link>
    </div>
    <var-button style="width: 100%" type="primary" native-type="submit"
      >注册</var-button
    >
  </var-form>
</template>

<script setup lang="ts">
import { Md5 } from 'ts-md5'
import { register, sendCode, validPhone } from '@/api'

const router = useRouter()

const validatePhone = async v => {
  if (!/^1[3-9]\d{9}$/.test(v)) return '手机号格式不正确'
  const res = await validPhone(v)
  return res || true
}

const showSendCode = ref(true)
const getCode = async () => {
  if (formData.value.phone.trim() === '') {
    Snackbar['error']('请输入手机号')
    return
  }
  await sendCode(formData.value.phone)
  showSendCode.value = false
}

const confirmPassword = ref('')
const formData = ref({
  phone: '',
  code: '',
  password: ''
})

const handleSubmit = async valid => {
  if (!valid) return
  await register({
    phone: formData.value.phone,
    code: formData.value.code,
    password: Md5.hashStr(formData.value.password)
  })
  Snackbar['success']('注册成功')
  router.push('/login')
}
</script>

<style scoped lang="scss"></style>
